package com.liu.resume.httpapi.rxjava;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;

/**
 * 类、方法注释 处理最终请求结果的观察者形态
 *
 * @author creat  by:yts 2016/9/10
 * @author update by:
 */
public class ResponseObserver implements rx.Observer<ResponseBody> {


    private ResponseCallBack<JSONObject> listener;

    public ResponseObserver(ResponseCallBack<JSONObject> listener) {
        this.listener = listener;
    }

    @Override
    public void onCompleted() {//完成时

    }

    @Override
    public void onError(Throwable e) {
        listener.onError(e);
    }

    @Override
    public void onNext(ResponseBody res) {//思路考虑  想把这个作为原始解析  封装。
                                          // 给予多接口去实现
        String responseBody = "";
        try {
            responseBody = res.string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            String response_code = jsonObject.getString("response_code");
            if (response_code.equals("1")) {//1 则表示返回成功的数据
                listener.onNext(jsonObject);
            } else {
                JSONObject result = jsonObject.getJSONObject("result");
                String mess = result.getString("reason");
                listener.onFailed(mess);
            }
        } catch (JSONException e) {
            listener.onError(e);
        }
    }
}